import 'dart:convert';
import 'dart:typed_data';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:pointycastle/asymmetric/pkcs1.dart';
import 'package:pointycastle/asymmetric/rsa.dart';
// import 'package:pointycastle/paddings/pkcs1.dart';
import 'package:asn1lib/asn1lib.dart';
import 'package:convert/convert.dart';
import 'dart:typed_data';
import 'dart:convert';

const MAX_ENCRYPT_BLOCK = 117;

RSAPublicKey parsePublicKeyFromPem(String pem) {
  final lines = pem.split('\n');
  final header = lines.first;
  final footer = lines.last;
  final base64 = lines.sublist(1, lines.length - 1).join('');
  final asn1Parser = ASN1Parser(base64Decode(base64));
  final asn1Sequence = asn1Parser.nextObject() as ASN1Sequence;

  final modulus = asn1Sequence.elements![0] as ASN1Integer;
  final exponent = asn1Sequence.elements![1] as ASN1Integer;

  return RSAPublicKey(modulus.valueAsBigInteger!, exponent.valueAsBigInteger!);
}

Uint8List rsaEncrypt(Uint8List data, RSAPublicKey publicKey) {
  final cipher = PKCS1Encoding(RSAEngine())
    ..init(true, PublicKeyParameter<RSAPublicKey>(publicKey));

  final inputLen = data.length;
  final out = BytesBuilder();
  int offset = 0;

  while (inputLen - offset > 0) {
    Uint8List cache;
    if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
      cache = cipher.process(Uint8List.sublistView(data, offset, offset + MAX_ENCRYPT_BLOCK));
    } else {
      cache = cipher.process(Uint8List.sublistView(data, offset, inputLen));
    }
    out.add(cache);
    offset += MAX_ENCRYPT_BLOCK;
  }

  return out.toBytes();
}

String encrypt(String content, String pemKey) {
  if (content.isEmpty || pemKey.isEmpty) return content;
  
  final publicKey = parsePublicKeyFromPem(pemKey);
  final data = utf8.encode(content);
  final encryptedData = rsaEncrypt(Uint8List.fromList(data), publicKey);
  
  return base64Encode(encryptedData);
}

// void main() {
//   const publicKeyPem = '''
// -----BEGIN PUBLIC KEY-----
// MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvWZP1XnE+0KwunbsGH57
// ...
// -----END PUBLIC KEY-----
// ''';

//   final content = '需要加密的内容';
//   final encryptedContent = encrypt(content, publicKeyPem);
//   print(encryptedContent);
// }
